<template>
  <!--流量检索 -->
  <div id="trafficRetrieval">
    <search-table
      :columns="listCol" 
      :data="retData.list"
      :total="retData.total"
      :page.sync="queryParams.pageIndex"
      :size.sync="queryParams.pageSize"
      @change-page="changePage"
      @change-size="changeSize"
    >
      <template slot="datePickert-group">
        <DatePicker
          :editable="false"
          type="datetimerange"
          :value="queryParams.Dates"
          format="yyyy-MM-dd HH:mm:ss"
          placement="bottom-start"
          confirm
          ref="datePicker"
          placeholder="选择日期"
          transfer
          @on-ok="clickOkBtn"
          @on-clear="clickClearBtn"
          @on-change="changeDates"
        ></DatePicker>
      </template>
      <template slot="select-group">
        <Select filterable
          v-model="queryParams.key"
          placeholder="请选择字段"
          clearable
          filterable
          transfer
          style="width: 150px; margin-right: 0px"
          class="condition_width_150"
        >
          <Option
            v-for="(item, index) in sessionData"
            :value="item.dto || item.key"
            :key="index"
            @click.native="getMoreParams(item)"
            >{{ item.value }}</Option
          >
        </Select>
        <Select filterable
          v-model="queryParams.condition"
          placeholder=""
          transfer
          class="condition_width"
          style="width: 90px !important; margin-right: 0px"
        >
          <Option
            v-for="(value, key, index) in conditionItem"
            :key="index"
            :value="key"
            >{{ value }}</Option
          >
        </Select>
        <Select filterable
          v-if="selectType == 'select'"
          v-model="queryParams.selectValue"
          placeholder=""
          clearable
          transfer
          class="condition_width_150"
          style="width: 150px; margin-right: 0px"
        >
          <Option
            v-for="(item, index) in sessionSelectValue"
            :value="item.id"
            :key="item.id || index"
            >{{ item.name }}</Option
          >
        </Select>
        <Input
          v-else
          v-model.trim="queryParams.value"
          placeholder=""
          clearable
          class="condition_width_150"
          style="width: 150px; margin-right: 0px"
        ></Input>
        <Button
          type="info"
          :disabled="
            !(queryParams.value || queryParams.selectValue) && !queryParams.key
          "
          style="height: 32px; border-radius: unset; margin-bottom: 2px"
          @click="addQueryParams"
          >
          <Icon type="ios-add" size="14" />
          <!-- style="height: 32px; border-radius: unset; margin-bottom: 6px" -->
          添加过滤
        </Button>
      </template>
      <template slot="button-last_group">
        <Dropdown trigger="click" @on-click="downloadItem">
          <Button
            type="info"
            shape="circle"
            :disabled="queryParams.Dates.length == 0 && queryFiltering.length == 0"
          >
            <Icon type="ios-cloud-download-outline" size="14" />
            下载数据包
          </Button>
          <template #list>
            <DropdownMenu>
              <DropdownItem name="pcap">PCAP</DropdownItem>
              <DropdownItem name="pcapng">PCAPNG</DropdownItem>
            </DropdownMenu>
          </template>
        </Dropdown>
        <!-- 在线分析功能还没完善，暂时屏蔽 -->
        <Button type="info" shape="circle" @click="toLineAnalysis" v-if="false">
          <Icon type="ios-folder-outline" size="14" />
          在线分析
        </Button>
        <Button shape="circle" @click="refreshList">
          <Icon type="md-refresh" size="14" />
          刷新
        </Button>
        <!-- <Button shape="circle">
          <Icon type="md-refresh" size="14" />
          重置
        </Button> -->
      </template>
      <template slot="filter-tag-list">
        <div style="margin-bottom: 10px" v-if="queryFiltering.length > 0">
          <Tag
            type="border"
            color="primary"
            closable
            v-for="(item, index) in queryFiltering"
            :key="index"
            @on-close="handleDeleteTag(item)"
          >
            {{
              item.key + " " + conditionText(item.condition) + " " + item.value
            }}
          </Tag>
        </div>
      </template>
    </search-table>
    <Modal
      :value="progress.show"
      title="下载进度"
      width="500"
      :mask-closable="false"
      footer-hide
      @on-visible-change="change"
    >
      <Progress
        :percent="progress.progress"
        :stroke-width="20"
        :status="progress.status"
        text-inside
      />
    </Modal>
  </div>
</template>
<script>
//	import Cookies from 'js-cookie'
import { reportStatis, downloadFile } from '@/api/compitionStatic';
import {flowMachlake ,fullFlowDown,sessionDetailKey,sessionKeyValue,trafficArchivingDown,trafficArchivingDownFileId,trafficArchivingDownProgress} from '@/api/integration3d';
// import tableBody from './tableListComponent';
import groupMixin from '@/mixin/groupMixin';
import LevelMixin from '@/mixin/levelMixin';
import SearchTable from '@/components/SearchTable/SearchTable';
import PackageProgress from '@/components/package-progress/package-progress.vue'

export default{
  name: 'trafficRetrieval',
  props: ['sceneId', 'poll','networkBeParams','trafficRetrievalParams'],
  mixins: [groupMixin, LevelMixin],
  data() {
    const d = function(val) {
      this.getRankingStatic(null, null, val);
    }.bind(this);

    return {
      queryParams: {
        condition: 'eq', //条件表达式 and 或者 or 默认and ,
        Dates: [],
        endTime: '', //结束时间 ,
        startTime: '',//开始时间
        offlineTaskId: '', //离线任务Id
        pageIndex: 1,
        pageSize: 10,
        key:'',
        value:'',
        selectValue:'',
        sessionQueryConditionList: [
          // {
          //   condition: '',//条件表达式 = 和 != ,
          //   key: '', //查询条件 
          //   value: '', //值
          // }
        ],
        projectId :this.$route.query.prjid,
        // projectId: "J6c710a699fd4d83a7418c468bf5b562",
      },
      retData: {
        total: 0,
        list: []
      },
      modalTitle: '',
      topoTargetData: [],
      reportModal: false,
      c: false,
      listCol: [
               {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '记录时间',
          key: 'report_time',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: true,
          minWidth: 140,
          // placement: 'top-left',
          // order: 1
          // render:(h,params)=> {
          //   return h('div', new Date(params.row.report_time))
          // },
          // filter:(data)=>{
          //   let reportTime = new Date(data);
          //   // reportTime.toISOString().slice(0, 19).replace("T", " ")reportTime.toISOString().slice(0, 19).replace("T", " ")
          //   let formattedReportTime = reportTime.toISOString().replace('T', ' ').split('.')[0];
          //   return formattedReportTime;
          // }
        },
        {
          title: '开始时间',
          key: 'start_time',//
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: true,
          minWidth: 140,
          // placement: 'top-left',
          // order: 1
          // filter:(data)=>{
          //   let startTime = new Date(data);
          //   let formattedStartTime = startTime.toISOString().replace('T', ' ').split('.')[0];
          //   return formattedStartTime;
          // }
        },
        {
          title: '持续时间(ms)',
          key: 'duration', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: true,
          minWidth: 140
        },
        // {
        //   title: '接口名称',
        //   key: 'interface', //
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   sortable: true,
        //   minWidth: 140
        // },
        {
          title: '源IP',
          key: 'ipv4_initiator', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 140
        },
        {
          title: '源IP位置',
          key: 'ip_locality_initiator', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 140
        },
        {
          title: '源端口',
          key: 'port_initiator', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 140
        },
        // {
        //   title: '源IP地址组',
        //   key: 'hostgroup_id_initiator', //
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   minWidth: 140
        // },
        {
          title: '目的IP',
          key: 'ipv4_responder', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140
        },
        {
          title: '目的IP位置',
          key: 'ip_locality_responder', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140
        },
        {
          title: '目的端口',
          key: 'port_responder', //
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140
        },
        // {
        //   title: '目的IP地址组',
        //   key: 'hostgroup_id_responder', //
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   width: 140
        // },
        {
          title: 'NAT源IP',
          key: 'company',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140
        },
        {
          title: 'NAT源端口',
          key: 'attackTypeName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140
        },
        {
          title: 'NAT目的IP',
          key: 'defenseTypeName',
          width: 140,
          align: 'center',
          tooltip: true,
          ellipsis: true,
        },
        {
          title: 'NAT目的端口',
          key: 'defenseTypeName',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          ellipsis: true,
        },
        {
          title: '正向字节数',
          key: 'upstream_bytes',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          ellipsis: true,
          sortable: true,
        },
        {
          title: '反向字节数',
          key: 'downstream_bytes',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          ellipsis: true,
          sortable: true,
        },
        {
          title: '总字节数',
          key: 'total_bytes',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          sortable: true,
          ellipsis: true,
        },
        {
          title: '正向包数',
          key: 'upstream_packets',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          sortable: true,
          ellipsis: true,
        },
        {
          title: '反向包数',
          key: 'downstream_packets',
          minWidth: 140,
          align: 'center',
          tooltip: true,
          sortable: true,
          ellipsis: true,
        },
        {
          title: '总包数',
          key: 'total_packets',//
          minWidth: 140,
          align: 'center',
          tooltip: true,
          sortable: true,
          ellipsis: true,
        },
        {
          title: '正payload字节数',
          key: 'upstream_payload_bytes', //
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '反payload字节数',
          key: 'downstream_payload_bytes',//
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'payload总字节数',
          key: 'total_payload_bytes',//
          tooltip: true,
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '正向payload数据包',
          key: 'upstream_payload_packets',//
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '反向payload数据包',
          key: 'downstream_payload_packets',//
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'payload总数据包',
          key: 'total_payload_packets',//
          tooltip: true,
          sortable: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '新建会话',
          key: 'established_sessions', //
          tooltip: true,
          sortable: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'TCP同步数据包',
          key: 'tcp_syn_packets', //
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'TCP同步确认数据包',
          key: 'tcp_syn_ack_packets', //
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'TCP同步重置数据包',
          key: 'tcp_syn_rst_packets',//
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'TCP客户端重传包数',
          key: 'tcp_client_retransmission_packets', //
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '客户端重传率',
          key: 'tcp_client_retransmission_rate',//
          tooltip: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'TCP服务端重传包数',
          key: 'tcp_server_retransmission_packets',//
          tooltip: true,
          align: 'center',
          sortable: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '服务端重传率',
          key: 'tcp_server_retransmission_rate',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'ETH类型',
          key: 'ethernet_type',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '源MAC',
          key: 'ethernet_initiator',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '目的MAC',
          key: 'ethernet_responder',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '网络层协议',
          key: 'ethernet_protocol', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: 'VLANID',
          key: 'vlan_id',
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '传输层协议',
          key: 'ip_protocol', //
          tooltip: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '应用层协议',
          key: 'l7_protocol', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '应用分类',
          key: 'application_category_id', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '应用子分类',
          key: 'application_subcategory_id', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '应用',
          key: 'application_name',
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '源IP国家',
          key: 'country_id_initiator', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '源IP省份',
          key: 'province_id_responder', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '源IP城市',
          key: 'city_id_initiator', //
          tooltip: true,
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '目的IP国家',
          key: 'country_id_responder', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '目的IP省份',
          key: 'province_id_responder', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '目的IP城市',
          key: 'city_id_responder', //
          tooltip: true,
          align: 'center',
          ellipsis: true,
          minWidth: 170
        },
        {
          title: '客户端网络时延(ms)',
          key: 'tcp_client_network_latency',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          sortable: true,
          minWidth: 170
        },
        {
          title: '服务端网络时延(ms)',
          key: 'tcp_server_network_latency',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          sortable: true,
          minWidth: 170
        },
        {
          title: '服务端响应时延(ms)',
          key: 'server_response_latency',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          sortable: true,
          minWidth: 170
        },
        {
          title: 'TCP客户端零窗口包数',
          key: 'tcp_client_zero_window_packets',//
          tooltip: true,
          align: 'center',
          ellipsis: true,
          sortable: true,
          minWidth: 190
        },
        {
          title: 'TCP客户端零窗口占比',
          key: 'defenseTypeName',
          tooltip: true,
          ellipsis: true,
          // sortable: true,
          align: 'center',
          minWidth: 190
        },
        {
          title: 'TCP服务端零窗口包数',
          key: 'tcp_server_zero_window_packets',//
          tooltip: true,
          ellipsis: true,
          align: 'center',
          sortable: true,
          minWidth: 190
        },
        {
          title: 'TCP服务端零窗口占比',
          key: 'defenseTypeName',
          tooltip: true,
          ellipsis: true,
          align: 'center',
          // sortable: true,
          minWidth: 190
        },
        {
          title: 'TCP客户端丢包字节数',
          key: 'defenseTypeName',
          tooltip: true,
          ellipsis: true,
          align: 'center',
          sortable: true,
          minWidth: 190
        },
        {
          title: 'TCP服务端丢包字节数',
          key: 'defenseTypeName',
          tooltip: true,
          ellipsis: true,
          align: 'center',
          sortable: true,
          minWidth: 190
        },
        {
          title: 'TCP连接状态',
          key: 'defenseTypeName',
          tooltip: true,
          ellipsis: true,
          align: 'center',
          sortable: true,
          minWidth: 170
        },
        // {
        //   title: '体征序列',
        //   key: 'packet_sigseq',
        //   tooltip: true,
        //   ellipsis: true,
        //   align: 'center',
        //   sortable: true,
        //   minWidth: 170
        // },

        // 暂时干掉
        // {
        //   title: '操作',
        //   align: 'center',
        //   placement: 'top-right',
        //   fixed:'right',
        //   action: true,
        //   minWidth: 160,
        //   render: (h, params) => {
        //     return h(
        //       'div',
        //       {
        //         style: {
        //           width: '150px'
        //         }
        //       },
        //       [
        //         h(
        //           'Button',
        //           {
        //             props: {
        //               type: 'primary',
        //               size: 'small'
        //             },
        //             style: {
        //               marginRight: '5px',
        //               // display: params.row.type === 1 ? 'inline-block' : 'none'
        //             },
        //             on: {
        //               click: () => {
        //                 // console.log('====点击数据包');
        //                 console.log('====点击在线分析');
        //                 this.toLineAnalysis(params.row);
        //               }
        //             }
        //           },
        //           '在线分析'
        //         ),
        //       ]
        //     );
        //   }
        // }
      ],
      reportInitObj: {
        Button: [],
        Input: [],
        Select: [],
        DatePicker: {
          isShow: false,
          fnName: d
        },
        Page: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        listData: []
      },
      timeout: {},
      industryList: [],
      attackList: [],
      extent4InjuryData: [],
      extent4DefenseTypesData: [],
      ruleList: [],
      companyList: [],

      // 
      progress: {
        show: false,
        progress: 0,
        status: 'active'
      },

      // 筛选值
      queryObj: {},
      // 查询字段太长了，重新定义赋值
      queryFiltering: [],
      conditionObj: {
        eq: '=',
        ne: '!=',
        lt: '<',
        le: '<=',
        gt: '>',
        ge: '>=',
        like: 'like',
        match: 'Match',
      },

            // 根据接口 key 和运算符
      sessionData: [],
      // 获取动态运算符
      conditionItem: {
        eq: '=',
        ne: '!=',
      },
      // 根据key 值获取 value  仅在有下拉情况下有内容
      sessionSelectValue: [],
      selectType:'text'
    };
  },
  computed: {
    filterTeamList() {
      return this.teamList.filter((item) => item.name !== '目标方管理员组');
    }
  },
  components: {
    // 'table-body': tableBody,
    SearchTable,
    PackageProgress
  },
  watch: {},
  created () {
    if (this.trafficRetrievalParams.showFlag) {
      let { startTime, endTime } = this.trafficRetrievalParams
      this.queryParams.Dates = [startTime, endTime]
      this.queryParams.startTime = startTime
      this.queryParams.endTime = endTime
      this.getFlowMachlake()
    } else {
      this.refreshList()
    }
  },
  beforeDestroy() {
    // clearTimeout(this.timeout);
     this.timer && clearTimeout(this.timer)
  },
  mounted () {
    this.sessionKeyValue()
    // this.sessionDetailKey()
    // this.getFlowMachlake() // 默认不开启查询
  },
  methods: {
    initQueryParams () {
      this.queryParams = {
        condition: 'eq', //条件表达式 and 或者 or 默认and ,
        Dates: [],
        endTime: '', //结束时间 ,
        startTime: '',//开始时间
        offlineTaskId: '', //离线任务Id
        pageIndex: 1,
        pageSize: 10,
        key: '',
        value: '',
        sessionQueryConditionList: [
          // {
          //   condition: '',//条件表达式 = 和 != ,
          //   key: '', //查询条件 
          //   value: '', //值
          // }
        ],
        projectId: this.$route.query.prjid,
        // projectId: "Jf9bb58b53934df183b83878f74316e6",
      }
      this.queryFiltering = []
    },
    // 刷新
    refreshList () {
      this.initQueryParams()
      this.getFlowMachlake()
    },
    clickClearBtn () {
     this.changeDates()
      this.clickOkBtn()
    },
    changeDates (timeList) {
      console.log('hangeDates ~ timeList:', timeList)
      if (timeList && timeList[0]) {
        this.queryParams.Dates = timeList
        this.queryParams.startTime = timeList[0]
        this.queryParams.endTime = timeList[1]
      } else {
        this.queryParams.Dates = []
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },

    clickOkBtn () {
      this.getFlowMachlake()
      // this.isClickOkBtn = true
    },
    // switchOpenChange(){},

    //在线分析
    toLineAnalysis (row) {
      console.log('=====点击分析');
       this.$router.push({
        path: '/lineAnalysis',
        query: {
          sceneName:row.name || '点击分析',
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page,
        }
      });
    },

    // 数据包
    toPacketAnalysis (row) {
      this.$router.push({
        name: 'packetAnalysis',
        query: {
          sceneName: row.name || '护网数据包',
          sceneId: row.sceneId || '123',
          projectId: row.projectId || '456',
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page
        }
      });
    },

    
    // // 流量分析
    // toPacketAnalysis (row) {
    //   this.$router.push({
    //     name: 'packetAnalysis',
    //     query: {
    //       sceneName: row.name || '护网数据包',
    //       sceneId: row.sceneId || '123',
    //       projectId: row.projectId || '456',
    //       name: this.$route.query.name,
    //       prjid: this.$route.query.prjid,
    //       id: this.$route.query.id,
    //       page: this.$route.query.page
    //     }
    //   });
    // },

    changeSize (size) {
      this.queryParams.pageSize = size;
      this.getFlowMachlake()
    },
    changePage (page) {
      this.queryParams.pageIndex = page;
      this.getFlowMachlake()
    },

    // 获取列表数据
    getFlowMachlake () {
      // let {startTime,endTime} = this.queryParams.startTime
      // if (
      //   new Date(endTime).getTime() -
      //   new Date(startTime).getTime() >
      //   60 * 60 * 1000
      // ) {
      //   this.$Message.error('起止时间间隔在一个小时内');
      //   return
      // }
      
      let params = {
        endTime: this.queryParams.endTime, //结束时间 ,
        startTime: this.queryParams.startTime,//开始时间
        projectId: this.queryParams.projectId,//开始时间
        offlineTaskId: '', //离线任务Id
        sessionQueryConditionList: this.queryParams.sessionQueryConditionList,
        pageIndex: this.queryParams.pageIndex,
        pageSize: this.queryParams.pageSize,
      }
      if (params.sessionQueryConditionList.length == 0) {
        delete params.sessionQueryConditionList
      }
      flowMachlake(params).then(res => {
        if (res.code == 1) {
          this.retData.list = res.data.items
          this.retData.total = res.data.total
        } else {
          this.retData.list = []
          this.retData.total = 0
           this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$message.error(error)
      })
    },


    // 下载
    downloadItem (val) {
      let project = this.$route.query.prjid
      let fileType = val == 'pcap' ? '0' : '2'  // 0: pcap, 2: pcapng 描述不同的文件格式。
      let data = {
        endTime: this.queryParams.endTime,
        startTime: this.queryParams.startTime,
        fileName: '', // 文件名称
        fileType: val,
        projectId: project,
        offlineTaskId: "",
        queryCondition: this.queryParams.sessionQueryConditionList,
      }
      if (data.queryCondition.length == 0) {
        delete data.queryCondition
      }
      trafficArchivingDown(data).then(res => {
        if (res.code == 1) {
          // this.downloadDrillReport(res.data, val)
          // this.trafficArchivingDownProgress(res.data, val)  // 暂不用进度
          this.trafficArchivingDownFileId(res.data, val)
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    trafficArchivingDownFileId(taskId, val){
      let progress = 0
      trafficArchivingDownFileId(taskId).then(res=>{
        if(res.code == 1){
          this.timer && clearTimeout(this.timer)
          if(res.data.fileState == 'success'){
            this.downloadDrillReport(res.data.fileId, val)
          }else if(res.data.fileState == 'error'){
            // this.timer && clearTimeout(this.timer)
            this.$Message.warning(res.data.fileMsg || '下载失败！找不到文件信息')
          }else if(res.data.fileState == 'loading'){
            // this.timer && clearTimeout(this.timer)
            this.timer = setTimeout(() => {
              this.trafficArchivingDownFileId(taskId, val)
            },10 * 1000)
          }
          this.generatedownFileProgress(progress)
        }else{
          this.$Message.warning(res.message)
        }
      }).catch(error=>{
        console.log(error);
      })
    },


     downloadDrillReport (taskId, val) {
      // this.progress.show = true
      let flag = false // 不存在文件，进度条控制为0
      downloadFile(taskId, this.downFileProgress).then(res => {
        console.log('🚀 ~ downloadFile ~ res:', res)
        this.totalProgress = 0
        // if (res.type == 'application/octet-stream') {
        if (!res.code) {
          const link = document.createElement("a");
          const href = window.URL.createObjectURL(res);
          link.href = href;
          link.download = `${this.$route.query.name}-数据包.${val}`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        } else {
          flag = true
          this.progress.status = 'wrong'
          // this.$Message.error('下载文件失败!不存在文件数据！');
          this.$Message.error('任务未完成或没有产生文件，请稍后重试');
        }
      }).catch(error => {
        this.progress.status = 'wrong'
        this.$Message.error('下载失败!');
      }).finally(() => {
        if (flag) {
          this.progress.progress = 0
        } else {
          this.progress.progress = 100
        }
        setTimeout(() => {
          this.progress.show = false
          this.progress.status = 'active'
          this.progress.progress = 0
        }, 2000)

      })
    },




    // 下载文件
    downloadFile(fileId){
      downloadFile(fileId).then(data => {
          if(!data.code){
              const downloadElement = document.createElement("a");
              const href = window.URL.createObjectURL(data);
              downloadElement.href = href;
              downloadElement.download = file.name;
              document.body.appendChild(downloadElement);
              downloadElement.click();
              document.body.removeChild(downloadElement); // 下载完成移除元素
              window.URL.revokeObjectURL(href); // 释放掉blob对象
          }else{
              this.$Message.error(data.message);
          }
      }).catch(error => {
          this.$Message.error('下载报告失败!');
      })
    },


    trafficArchivingDownProgress(taskId, val){
       let progress = 0
      trafficArchivingDownProgress(taskId).then(res=>{
        if(res.code == 1){
          progress = res.data.executionProgress
          if(progress == 100){
            // 清除定时器
            this.timer && clearTimeout(this.timer)
            // 下载文件
            this.downloadDrillReport(res.data.id, val)
          }else{
            // 定时器持续请求 到了100 清除定时器
            this.timer && clearTimeout(this.timer)
            this.timer = setTimeout(() => {
              this.trafficArchivingDownProgress(taskId, val)
            },3 * 1000)
          }
        }else{
          this.timer && clearTimeout(this.timer)
          this.$Message.warning(res.message)
        }
        this.generatedownFileProgress(progress)
      }).catch(error =>{
        this.$Message.error(error)
      })
    },

    // 再定义一个生成进度显示
    generatedownFileProgress(progress=0){
      this.progress.show = true
      this.progress.progress = progress;
    },

    downloadDrillReport_old (taskId, val) {
      let sceneId = this.$route.query.id;
      // this.progress.show = true
      let flag = false // 不存在文件，进度条控制为0
      fullFlowDown(taskId, this.downFileProgress).then(res => {
        this.totalProgress = 0
        if (res.type == 'application/octet-stream') {
          const link = document.createElement("a");
          const href = window.URL.createObjectURL(res);
          link.href = href;
          link.download = `${this.$route.query.name}-数据包.${val}`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        } else {
          flag = true
          this.progress.status = 'wrong'
          // this.$Message.error('下载文件失败!不存在文件数据！');
          this.$Message.error('任务未完成或没有产生文件，请稍后重试');
        }
      }).catch(error => {
        this.progress.status = 'wrong'
        this.$Message.error('下载失败!');
      }).finally(() => {
        if (flag) {
          this.progress.progress = 0
        } else {
          this.progress.progress = 100
        }
        setTimeout(() => {
          this.progress.show = false
          this.progress.status = 'active'
          this.progress.progress = 0
        }, 2000)

      })
    },
    // 进度
    downFileProgress (progress) {
      let currentProgress = progress.loaded * 1; //B单位
      if (this.totalProgress) {
        this.totalProgress += currentProgress
      } else {
        this.totalProgress = currentProgress
      }
      currentProgress = this.totalProgress - currentProgress ? currentProgress : currentProgress / 2;
      let rate = (((this.totalProgress - currentProgress) / this.totalProgress) * 100).toFixed(2) * 1;
      if (!this.rate || rate > this.rate) {
        this.progress.progress = rate;
      }
    },

    change (val) {
      this.progress.show = val
    },

    
    // 获取协议
    sessionDetailKey () {
      sessionDetailKey().then(res => {
        if (res.code == 1) {
          this.queryObj = res.data
          console.log('🚀 this.queryObj:', res.data)
        } else {
          this.queryObj = {}
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

     // 初始化条件
    initSessionKeyValue () {
      this.queryParams.key = ''
      this.queryParams.value = ''
      this.queryParams.selectValue = ''
      this.queryParams.condition = 'eq'
      this.sessionSelectValue = []
      this.selectType = 'text'
      this.conditionItem = {
        eq: '=',
        ne: '!=',
      }
    },

    addQueryParams () {
      if (!this.queryParams.key || !(this.queryParams.value || this.queryParams.selectValue)) return;
      this.queryFiltering.push({
        key: this.queryParams.key,
        value: this.queryParams.value || this.queryParams.selectValue,
        condition: this.queryParams.condition,
        index: this.queryFiltering.length + 1
      })
      this.initSessionKeyValue()
      this.changeQuery()

    },

    handleDeleteTag (row) {
      let index = this.queryFiltering.findIndex(item => item.index == row.index);
      if (index > -1) {
        this.queryFiltering.splice(index, 1)
      }
      this.changeQuery()
    },

    // 条件变化赋值
    changeQuery () {
      this.queryParams.sessionQueryConditionList = this.queryFiltering.map(item => {
        return {
          key: item.key,
          value: item.value,
          condition: item.condition,
        }
      })
      console.log('=== this.queryParams==', this.queryParams);
      this.getFlowMachlake()
    },


    
    getMoreParams (item) {
      console.log('🚀 val:', item)
    item.conditionList.forEach(items => {
      this.conditionItem[items] = this.conditionObj[items]
    });
        //  原来根据 key 走接口获取数据 现在直接在原来接口一次返回 取jsonArray
      // this.sessionKeyValue (item.key,item.type)
    this.selectType = item.type
    this.sessionSelectValue = item.jsonArray
    //   this.sessionKeyValue('l7ProtocolId', 'select')
    //   this.selectType = 'select'
    },

        // 根据值获取筛选值
    sessionKeyValue (key, type) {
      if (type == 'text') return;
      let params = {
        // TrafficArchiving  流量归档 TrafficRetrieval 流量检索(会话详情)
        capacity: 'TrafficRetrieval',
        key: key || '',
        pageIndex: 1,
        pageSize: 99999
      }
      sessionKeyValue(params).then(res => {
        if (res.code == 1) {
          if (!key) {
            this.sessionData = res.data.items
            console.log('🚀 ~ file: trafficRetrieval.vue:1205 ~ sessionKeyValue ~ this.sessionData:', this.sessionData)
          } else {
            this.sessionSelectValue = res.data.items
          }
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },




    // 符号转换
    conditionText (val) {
      let str = ''
      switch (val) {
        case "eq": str = '='; break;
        case "ne": str = '!='; break;
        case "lt": str = '<'; break;
        case "le": str = '<='; break;
        case "gt": str = '>'; break;
        case "ge": str = '>='; break;
        case "like": str = 'like'; break;
        case "match": str = 'match'; break;
        default: str = '-'; break;
      }
      return str;
    },

    downloadFile_old (file) {
      downloadFile(file.id)
        .then((data) => {
          if (!data.se.sessionQueryConditionList.code) {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = file.name;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error('下载报告失败!');
        });
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
#trafficRetrieval .ivu-table-overflowX {
  overflow-x: auto;
}
</style>
<style scoped>
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}
.targetHeader {
  padding: 10px;
  margin-bottom: 10px;
}
</style>
